package com.dingnate.framework.springmvn.scaner;

import com.dingnate.framework.springmvn.func.Func1;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DirectoryScanner {
    private final String root;

    public DirectoryScanner(String file) {
        this.root = file;
    }

    public <T> List<T> scan(Func1<T> Filter) {
        ArrayList<T> files = new ArrayList<>();
        File rootFile = new File(this.root);
        if (!rootFile.exists()) {
            throw new RuntimeException("root:" + root + "is not exist!");

        }
        doScan(rootFile, files, Filter);
        return files;
    }

    private <T> void doScan(File root, List<T> files, Func1<T> filter) {
        T o = filter.call(root);
        if (o != null) {
            if (root.isDirectory()) {
                for (File file : root.listFiles()) {
                    doScan(file, files, filter);
                }
            } else {
                files.add(o);
            }
        }
    }
}
